const fs = require('fs');
const path = require('path');
const ExcelJS = require('exceljs');

// 加载 JSON 映射表
const docMap = require('./docMap.json');

// 用于保存表格数据
const tableData = [];

// 所有路径转成对象数组，包含层级信息
Object.entries(docMap).forEach(([filePath, title]) => {
    if (!filePath.startsWith('docs/')) return;

    // 去掉 docs/ 后拆分路径
    const parts = filePath.replace(/^docs\//, '').split('/').filter(Boolean);

    if (parts.length === 0) return;

    const isFile = filePath.endsWith('.md');
    const levelTitles = parts.map((part, i) => {
        const fullPath = 'docs/' + parts.slice(0, i + 1).join('/') + (part.endsWith('.md') ? '' : '/');
        return docMap[fullPath] || part.replace(/\.md$/, '');
    });

    // 如果是文件，则最后一项是文件名
    if (isFile) {
        levelTitles[levelTitles.length - 1] = title;
    }

    // 构造一行数据
    const row = {};
    levelTitles.forEach((title, i) => {
        row[`level${i + 1}`] = title;
    });
    row.levelCount = levelTitles.length;

    tableData.push(row);
});

// 合并单元格逻辑（生成 rowspan）
const maxLevel = Math.max(...tableData.map(d => d.levelCount));
for (let i = maxLevel; i >= 1; i--) {
    let sameCount = 1;
    for (let j = 1; j < tableData.length; j++) {
        const prev = tableData[j - 1][`level${i}`];
        const curr = tableData[j][`level${i}`];

        if (prev === curr && tableData[j - 1].sameUpTo !== i) {
            sameCount++;
        } else {
            if (sameCount > 1) {
                tableData[j - 1][`rowspan${i}`] = sameCount;
                for (let k = j - sameCount + 1; k < j; k++) {
                    tableData[k].sameUpTo = i;
                }
            }
            sameCount = 1;
        }
    }
    if (sameCount > 1) {
        tableData[tableData.length - 1][`rowspan${i}`] = sameCount;
        for (let k = tableData.length - sameCount; k < tableData.length; k++) {
            tableData[k].sameUpTo = i;
        }
    }
}

// 创建一个新的工作簿和工作表
const workbook = new ExcelJS.Workbook();
const worksheet = workbook.addWorksheet('文档结构');

// 添加表头
for (let i = 1; i <= maxLevel; i++) {
    worksheet.getCell(1, i).value = `${i}级`;
    worksheet.getCell(1, i).font = { bold: true };
}

// 添加数据
tableData.forEach((row, rowIndex) => {
    for (let i = 1; i <= maxLevel; i++) {
        if (row.sameUpTo === i) continue;
        if (row[`rowspan${i}`]) {
            const cell = worksheet.getCell(rowIndex + 2, i);
            cell.value = row[`level${i}`];
            cell.fill = { type: 'pattern', pattern: 'solid', fgColor: { argb: 'FFD9EAD3' } }; // 可选：设置背景色
            cell.border = { top: { style: 'thin' }, left: { style: 'thin' }, bottom: { style: 'thin' }, right: { style: 'thin' } };
            cell.numFmt = '@'; // 设置为文本格式
            // worksheet.mergeCells(rowIndex + 2, i, rowIndex + 1 + row[`rowspan${i}`], i); // 合并单元格
        } else if (row[`level${i}`]) {
            const cell = worksheet.getCell(rowIndex + 2, i);
            cell.value = row[`level${i}`];
            cell.border = { top: { style: 'thin' }, left: { style: 'thin' }, bottom: { style: 'thin' }, right: { style: 'thin' } };
            cell.numFmt = '@'; // 设置为文本格式
        }
    }
});

// 自动调整列宽
worksheet.columns.forEach(column => {
    let maxLength = 0;
    column.eachCell({ includeEmpty: true }, (cell) => {
        const length = cell.value ? cell.value.toString().length : 10;
        if (length > maxLength) maxLength = length;
    });
    column.width = maxLength + 2; // 给每列增加一点额外的空间
});

// 写入 Excel 文件
workbook.xlsx.writeFile(path.join(__dirname, 'docStructure.xlsx'))
    .then(() => {
        console.log('✅ 已生成 Excel 文件：docStructure.xlsx');
    })
    .catch(error => {
        console.error('写入 Excel 文件时出错:', error);
    });